package cn.com.xuxiaowei.server.intercptor;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.NodeList;

import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

/**
 * @Description 身份验证拦截器
 * @Author weisl
 * @Date 2024-04-11 08:50
 */
@Slf4j
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private SAAJInInterceptor saa = new SAAJInInterceptor();

    private static final String USER_NAME = "admin";
    private static final String USER_PASSWORD = "123456";

    public AuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
        getAfter().add(SAAJInInterceptor.class.getName());
    }

    @SneakyThrows
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        log.info("来了哟！" + message);
        SOAPMessage mess = message.getContent(SOAPMessage.class);
        if (mess == null) {
            saa.handleMessage(message);
            mess = message.getContent(SOAPMessage.class);
        }
        SOAPEnvelope envelope = mess.getSOAPPart().getEnvelope();
        envelope.addNamespaceDeclaration("gat", "http://schemas.datacontract.org/2004/07/Gateway.Servicios");
        SOAPHeader header = null;
        try {
            header = mess.getSOAPHeader();
        } catch (SOAPException e) {
            log.error("getSOAPheader error:{}", e.getMessage(), e);
        }
        if (header == null) {
            throw new Fault(new IllegalAccessException("找不到Header,无法验证用户信息"));
        }
        NodeList username = header.getElementsByTagName("username");
        NodeList password = header.getElementsByTagName("password");
        if (username.getLength() < 1) {
            throw new Fault(new IllegalAccessException("找不到Header,无法验证用户信息"));
        }
        if (password.getLength() < 1) {
            throw new Fault(new IllegalAccessException("找不到Header,无法验证用户信息"));
        }
        String userName = username.item(0).getTextContent().trim();
        String passWord = password.item(0).getTextContent().trim();
        if (USER_NAME.equals(userName) && USER_PASSWORD.equals(passWord)) {
            log.info("admin auth success");
        } else {
            SOAPException soapException = new SOAPException("认证错误");
            log.info("admin auth failed");
            throw new Fault(soapException);
        }
    }

    // public boolean handleMessage(SOAPMessageContext context) {
    //     try {
    //         SOAPMessage message = context.getMessage();
    //         SOAPHeader header = message.getSOAPHeader();
    //         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
    //         if (header == null) {
    //             header = envelope.addHeader();
    //         }
    //         envelope.addNamespaceDeclaration("gat", "http://schemas.datacontract.org/2004/07/Gateway.Servicios");
    //         QName passwordQname = header.createQName("Password", "gat");
    //         QName userQname = header.createQName("User", "gat");
    //         // Here, I’m trying to add a QName with no namespace.
    //         QName qNameUserCredentials = new QName(XMLConstants.NULL_NS_URI, "MyHeader");
    //         SOAPHeaderElement userCredentials = header.addHeaderElement(qNameUserCredentials);
    //         SOAPHeaderElement password = header.addHeaderElement(passwordQname);
    //         password.addTextNode(this.password);
    //         SOAPHeaderElement username = header.addHeaderElement(userQname);
    //         username.addTextNode(this.username);
    //         userCredentials.addChildElement(password);
    //         userCredentials.addChildElement(username);
    //         message.saveChanges();
    //         StringWriter writer = new StringWriter();
    //         message.writeTo(new StringOutputStream(writer));
    //         System.out.println("SOAP message: \n" + writer.toString());
    //     } catch (SOAPException e) {
    //         System.out.println("Error occurred while adding credentials to SOAP header." + e.getMessage());
    //     } catch (IOException e) {
    //         System.out.println("Error occurred while writing message to output stream." + e.getMessage());
    //     }
    //     return true;
    // }

}
